#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <sys/socket.h>
#include <pthread.h>
#include <errno.h>
#include <unistd.h>
#include <fcntl.h>
#include "client.h"

int init()
{
	int sockfd;
	struct sockaddr_in addr;

	sockfd = socket(AF_INET, SOCK_STREAM, 0);
	addr.sin_family = AF_INET;
	addr.sin_port = htons(8888);
	inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr.s_addr);

	if(connect(sockfd, (struct sockaddr *)&addr, sizeof(addr)))
	{
		printf("connect error\n");
		close(sockfd);
		return 0;
	}
	printf("connect success\n");

	return sockfd;
}

void *sock_recv(void *argv)
{
	int len, sockfd;
	sockfd = *(int *)argv;
	char buf[1024], *str;

	while(1)
	{
		len = read(sockfd, buf, sizeof(buf));
		*(buf + len) = '\0';

/*		printf("recv:");
		for(int i = 0 ; i < len; i++)
			printf("%c", *(buf+i));
		printf("\n");
*/
		if(!strncmp(buf, "libr", 4))
		{
			str = unpack_lib(buf);
			printf("%s", str);
			free(str);
		}
		else if(!strncmp(buf, "filename", 8))
		{
			recv_file(sockfd, buf);
		}
		else
		{
			printf("%s\n", buf);
		}
	}
	return 0;
}

void recv_file(int sockfd, char *buf)
{
	int len, fd;
	char recv[1024], filename[100];

	strcpy(filename, buf + 9);

	fd = open(filename, O_WRONLY | O_CREAT, 0666);
	if(fd == -1)
		printf("creat file error\n");

	while((len = read(sockfd, recv, sizeof(recv))) > 0)
	{
		write(fd, recv, len);
	}

}

char *unpack_lib(char *buf)
{
	char *p, *head, *str;
	int len = 0;
	str = (char *)malloc(1024);

	head = buf;
	p = strchr(buf, '\0');
	head = ++p;

	while(*p != '\0')
	{
		p = strchr(head, '\0');
		len += sprintf(str+len, "%s\n", head);
		head = ++p;
	}
	sprintf(str+len, "%c", 0);

	return str;
}

void upload(char *filepath, int sockfd)
{
	char filename[1024], *p, sendbuf[1024];
	int fd, flen = 0;

	fd = open(filepath, O_RDONLY);
	if(fd == -1)
		printf("open file erroe\n");
	strcpy(filename ,filepath);
	p = filepath;
	while(p != NULL)
	{
		strcpy(filename, ++p);
		p = strchr(filename, '/');
	}

	sprintf(sendbuf, "filename%c%s", 0, filename);
	write(sockfd, sendbuf, sizeof(filename));

	while((flen = read(fd, sendbuf, sizeof(sendbuf))) > 0)
	{
		write(sockfd, sendbuf, flen);
	}
	
}

void client(int sockfd)
{
	char buf[1024];

	while(1)
	{
		gets(buf);
		write(sockfd, buf, sizeof(buf));
		if(!strcmp(buf, "quit"))
			break;
		if(!strncmp(buf, "upload ", 7))
		{
			upload(buf+7, sockfd);
		}
	}
}

